﻿using Newbe.TestDirector.Notification.Web.Domain;
using Newbe.TestDirector.Notification.Web.Entities;
using System;
using System.Data.Entity;
using System.Linq;

namespace Newbe.TestDirector.Notification.Web.Admin.MailScenes
{
    public partial class ShowColumnsConfig : System.Web.UI.Page
    {
        public IEfContext EfContext { get; set; }
        public IBugTableColumnsFactory BugTableColumnsFactory { get; set; }
        public IPrimaryKeyGenerator PrimaryKeyGenerator { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            ReloadGrid();
            if (!IsPostBack)
            {
                DropDownList1.DataSource = BugTableColumnsFactory.GeTableColumns().ToArray();
                DropDownList1.DataBind();
            }
        }

        private void ReloadGrid()
        {
            var id = Request["Id"];
            GridView1.DataSource = EfContext.MailScenes.Include(x => x.ShowColumns)
                .First(x => x.Id == id).ShowColumns.Select(x => x.TableColumn).ToArray();
            GridView1.DataBind();
        }

        protected void GridView1_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "RemoveShowColumn":
                    var data = GetData();
                    var colName = e.CommandArgument.ToString();
                    var col = data.ShowColumns.FirstOrDefault(x => x.TableColumn.ColumnName == colName);
                    if (col != null)
                    {
                        EfContext.ShowColumns.Remove(col);
                        EfContext.SaveChanges();
                        ReloadGrid();
                    }
                    break;
            }
        }

        private MailSceneEntity GetData()
        {
            var id = Request["Id"];
            return EfContext.MailScenes.Include(x => x.ShowColumns)
                .First(x => x.Id == id);
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            var data = GetData();
            var newCol = DropDownList1.SelectedValue;
            var newColDisplayName = DropDownList1.SelectedItem.Text;
            if (string.IsNullOrEmpty(newCol))
            {
                return;
            }
            if (data.ShowColumns.Any(x => x.TableColumn.ColumnName == newCol))
            {
                return;
            }
            data.ShowColumns.Add(new ShowColumnEntity
            {
                Id = PrimaryKeyGenerator.GetKey(),
                TableColumn = new TableColumn
                {
                    TableName = "BUG",
                    ColumnName = newCol,
                    DisplayName = newColDisplayName
                }
            });
            EfContext.SaveChanges();
            ReloadGrid();
        }
    }
}
